//
//  VideoViewController.m
//  BasketballClub
//
//  Created by 孙鸿吉 on 16/1/6.
//  Copyright © 2016年 孙鸿吉. All rights reserved.
//

#import "VideoViewController.h"
#import "VideoView.h"
#import "VideoCollectionViewCell.h"
#import "VideoHandle.h"
#import "VideoModel.h"
#import <MJRefresh.h>
#import <UIImageView+WebCache.h>
#import <AVOSCloud.h>
#import "RegistViewController.h"
#import "FindPWDViewController.h"
#import <UMSocial.h>
#import <MediaPlayer/MediaPlayer.h>
#import "CoreDataManager.h"
@interface VideoViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIGestureRecognizerDelegate>
@property(nonatomic,strong)VideoView *videoView;
@property (nonatomic,assign)NSInteger npcCount;
@property (nonatomic,strong)NSString *webViewUrl;
@property (nonatomic,strong)NSString *titless;
@end

@implementation VideoViewController
- (void)loadView
{
    self.videoView = [[VideoView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.view = self.videoView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.npcCount = 0;
    //注册重用
    [self.videoView.collectionView registerClass:[VideoCollectionViewCell class] forCellWithReuseIdentifier:@"VideoCollectionViewCell"];
    //遵守协议
    self.videoView.collectionView.dataSource = self;
    self.videoView.collectionView.delegate = self;
    //刷新数据
    [self upData];
    //下拉加载
    [self addData];
    //添加手势
    UIPanGestureRecognizer *panGR = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panGR)];
    [self.videoView.loginPresentView addGestureRecognizer:panGR];
    self.videoView.loginPresentView.userInteractionEnabled = YES;
    panGR.delegate = self;
    //登陆按钮方法
    [self.videoView.loginButton addTarget:self action:@selector(loginButtonAction) forControlEvents:UIControlEventTouchUpInside];
    //注册按钮方法
    [self.videoView.registButton addTarget:self action:@selector(registButtonAction) forControlEvents:UIControlEventTouchUpInside];
    //忘记密码按钮方法
    [self.videoView.findPWDButton addTarget:self action:@selector(findPWDButtonAction) forControlEvents:UIControlEventTouchUpInside];

}

#pragma mark - 返回Section
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
#pragma mark  - Items的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [VideoHandle sharedVideoHandle].VideoArray.count;
}
#pragma mark - 返回cell
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    VideoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"VideoCollectionViewCell" forIndexPath:indexPath];

    [cell.FButton addTarget:self action:@selector(FButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell.share addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
    VideoModel  *model =  [VideoHandle sharedVideoHandle].VideoArray[indexPath.item];
    [cell setCellDataWithModel:model];
    
    return cell;
}
#pragma mark - 手势方法
- (void)tapImageAction:(UIImageView *)sender
{
    MPMoviePlayerViewController *playerVC = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:self.webViewUrl]];
    [playerVC.moviePlayer prepareToPlay];
    playerVC.moviePlayer.shouldAutoplay = YES;
    [self presentViewController:playerVC animated:YES completion:nil];
}
#pragma mark - 实现 UICollectionViewDelegateFlowLayout 代理方法
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return CGSizeMake((SCREEN_WIDTH - 10*LAYOUT_SIZE)/2, (SCREEN_HEIGHT - 360*LAYOUT_SIZE_HEIGHT)/2);
    
}
#pragma mark - 是否可以点击
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
#pragma mark - 点击item执行的方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
        VideoCollectionViewCell *cell = (VideoCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    self.webViewUrl = cell.videoUrl;
    self.titless = cell.title.text;
    MPMoviePlayerViewController *playerVC = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:cell.videoUrl]];
    [playerVC.moviePlayer prepareToPlay];
    playerVC.moviePlayer.shouldAutoplay = YES;
    [self presentViewController:playerVC animated:YES completion:nil];
}
#pragma mark - 收藏按钮方法
- (void)FButtonAction:(UIButton *)sender
{
    VideoCollectionViewCell *cell = (VideoCollectionViewCell *)[[sender superview] superview];
    self.webViewUrl = cell.videoUrl;
    self.titless = cell.title.text;
    AVUser *currentUser = [AVUser currentUser];
    if (currentUser == nil) {
        [UIView animateWithDuration:0.5 animations:^{
            self.videoView.backgroundView.frame = CGRectMake(SCREEN_WIDTH/2 - (170 * LAYOUT_SIZE), 100 * LAYOUT_SIZE_HEIGHT, 320 * LAYOUT_SIZE, 350 * LAYOUT_SIZE_HEIGHT);
        }];
    }else{
        [sender setImage:[UIImage imageNamed:@"iconfont-htmal5icon24"] forState:UIControlStateNormal];
        NSIndexPath *index = [self.videoView.collectionView indexPathForCell:cell];
        VideoModel  *model =  [VideoHandle sharedVideoHandle].VideoArray[index.item];
        NSString *str = [NSString stringWithFormat:@"%@%@",model.title,currentUser.username];
        //保存收藏记录到本地
        [[LeanCloudService shareService] setIsCollectWithBool:YES andKey:str];
        [[LeanCloudService shareService] synchronize];
        NSString *string = [NSString stringWithFormat:@"%@isFirstLogin",currentUser.username];
        NSInteger number = [[LeanCloudService shareService] isFirstLoginWithKey:string];
        if (number == 1) {
            NSMutableArray *array = [NSMutableArray array];
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:self.titless,@"title",self.webViewUrl,@"url", nil];
            [array addObject:dic];
            [currentUser setObject:array forKey:@"BasketBall"];
            [currentUser signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                
            }];
            [[LeanCloudService shareService] setIsFirstLoginWithNumber:2 andKye:string];
            [[LeanCloudService shareService] synchronize];
        }else{
            NSMutableArray *array = [NSMutableArray array];
            array = [currentUser objectForKey:@"BasketBall"];
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:self.titless,@"title",self.webViewUrl,@"url", nil];
            [array addObject:dic];
            [currentUser setObject:array forKey:@"BasketBall"];
            [currentUser signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                
            }];
        }
    }
}
#pragma mark - 分享按钮方法
- (void)shareAction:(UIButton *)sender
{
    VideoCollectionViewCell *cell = (VideoCollectionViewCell *)[[sender superview] superview];
    self.webViewUrl = cell.videoUrl;
    self.titless = cell.title.text;
    [UMSocialData defaultData].extConfig.qqData.url = self.webViewUrl;
    [UMSocialData defaultData].extConfig.wechatSessionData.url = self.webViewUrl;
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"5693101667e58e370a00054f"
                                      shareText:self.titless
                                     shareImage:[UIImage imageNamed:@"app"]
                                shareToSnsNames:@[UMShareToSina,UMShareToQQ,UMShareToQzone,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToWechatFavorite]
                                       delegate:nil];

}
#pragma mark - 下拉刷新
-(void)upData
{
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshAction:)];
    self.videoView.collectionView.mj_header = header;
    [self.videoView.collectionView.mj_header beginRefreshing];
}

#pragma mark - 刷新事件
-(void)refreshAction:(MJRefreshHeader*)sender
{
    [VideoHandle sharedVideoHandle].VideoArray = nil;
    __weak typeof(self) weakSelf = self;
    [[VideoHandle sharedVideoHandle] getVideoDataFromNetWorkWithNumber:0 withBlock:^(BOOL isFinished) {
        if (isFinished) {
            [weakSelf.videoView.collectionView reloadData];
        }else{

        }
    }];
    [self.videoView.collectionView.mj_header endRefreshing];
}

#pragma mark - 上拉加载
- (void)addData
{
    self.videoView.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.npcCount++;
        __weak typeof(self) weakself = self;
        [[VideoHandle sharedVideoHandle]getVideoDataFromNetWorkWithNumber:self.npcCount withBlock:^(BOOL isFinished) {
            if (isFinished) {
                [weakself.videoView.collectionView reloadData];
            }else{
                
            }
            [self.videoView.collectionView.mj_footer endRefreshing];
        }];
    }];
}
- (void)panGR
{
    [UIView animateWithDuration:0.5 animations:^{
        self.videoView.backgroundView.frame = CGRectMake(SCREEN_WIDTH/2 - (170 * LAYOUT_SIZE), SCREEN_HEIGHT, 320 * LAYOUT_SIZE, 350 * LAYOUT_SIZE_HEIGHT);
    }];
}

#pragma mark - 登陆按钮方法实现
- (void)loginButtonAction
{
    [AVUser logInWithUsernameInBackground:self.videoView.usernameTF.text password:self.videoView.passwordTF.text block:^(AVUser *user, NSError *error) {
        if (user) {
            //登陆成功关闭登陆窗口
            self.videoView.usernameTF.text = nil;
            self.videoView.passwordTF.text = nil;
            [UIView animateWithDuration:0.5 animations:^{
                self.videoView.backgroundView.frame = CGRectMake(SCREEN_WIDTH/2 - (170 * LAYOUT_SIZE), SCREEN_HEIGHT, 320 * LAYOUT_SIZE, 350 * LAYOUT_SIZE_HEIGHT);
            }];
            AVUser *currentUser = [AVUser currentUser];
            NSString *string = [NSString stringWithFormat:@"%@isFirstLogin",currentUser.username];
            NSInteger number = [[LeanCloudService shareService] isFirstLoginWithKey:string];
            if (number == 1) {
                NSMutableArray *array = [NSMutableArray array];
                NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:self.titless,@"title",self.webViewUrl,@"url", nil];
                [array addObject:dic];
                [currentUser setObject:array forKey:@"BasketBall"];
                [currentUser signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                    
                }];
                [[LeanCloudService shareService] setIsFirstLoginWithNumber:2 andKye:string];
                [[LeanCloudService shareService] synchronize];
            }else{
                NSMutableArray *array = [NSMutableArray array];
                array = [currentUser objectForKey:@"BasketBall"];
                NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:self.titless,@"title",self.webViewUrl,@"url", nil];
                [array addObject:dic];
                [currentUser setObject:array forKey:@"BasketBall"];
                [currentUser signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                
                }];
            }
        }else{
            //登陆失败
            self.videoView.usernameTF.text = nil;
            self.videoView.passwordTF.text = nil;
            [self loginFiled];
        }
    }];
    
}
#pragma mark - 注册按钮方法实现
- (void)registButtonAction
{
    RegistViewController *registVC = [[RegistViewController alloc]init];
    [self presentViewController:registVC animated:YES completion:nil];
}
#pragma mark - 忘记密码按钮方法实现
- (void)findPWDButtonAction
{
    FindPWDViewController *findVC = [[FindPWDViewController alloc]init];
    [self presentViewController:findVC animated:YES completion:nil];
}


#pragma mark - 提示框(登录失败)
- (void)loginFiled
{
    CGFloat verison = [[[UIDevice currentDevice]systemVersion]floatValue];
    if (verison >= 8.0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"登录失败" message:@"请确认账号和密码是否匹配" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alert animated:YES completion:nil];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self dismissViewControllerAnimated:YES completion:nil];
        });
        
    }else{
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"登录失败" message:@"请确认账号和密码是否匹配" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
        [alertView show];
        
        [self performSelector:@selector(aftertimeAction:) withObject:alertView afterDelay:2.0];
    }
    
}

#pragma mark - 延迟2秒方法
- (void)aftertimeAction:(UIAlertView *)sender
{
    [sender dismissWithClickedButtonIndex:0 animated:YES];
    
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

@end
